/*
 * @FilePath: reset_zero.cpp
 * @Author: wyx
 * @Date: 2023-09-30 19:43:28
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-10-24 10:44:39
 * Copyright: 2023 xxxTech CO.,LTD. All Rights Reserved.
 * @Descripttion: 
 */

// #include"rx_ops9/reset_zero.hpp"

#include<iostream>
#include"rx_ops9/rx_ops9_node.hpp"

using namespace std;
using namespace std::chrono_literals;


int PPS_handle;
ppsCommSerial pps;


/**
 * @brief: Ops9定位初始化
 * @param {int&} fd
 * @param {char*} port 串口的路径
 * @param {int} baudrate
 * @return {*}
 */
int ppsCommSerial::pps_Init(int& fd, char* port, int baudrate)
{
    std::cout << "init " << port << " ...\n";
    fd = open(port, O_RDWR | O_NOCTTY | O_NDELAY);
    std::cout << fd << std::endl;
    if (fd == -1)
    {
        perror("open_port: Unable to open\n");
        return 0;
    }
    tcgetattr(fd, &termAttr);
    bzero(&termAttr, sizeof(termAttr));
    cfsetispeed(&termAttr, baudrate);
    cfsetospeed(&termAttr, baudrate);
    termAttr.c_cflag &= ~PARENB;
    termAttr.c_cflag &= ~CSTOPB;
    termAttr.c_cflag &= ~CSIZE;
    termAttr.c_cflag |= CS8;
    termAttr.c_cflag |= (CLOCAL | CREAD);
    termAttr.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
    termAttr.c_iflag &= ~(IXON | IXOFF | IXANY | ICRNL | ISTRIP);
    termAttr.c_oflag &= ~OPOST;
    termAttr.c_cc[VMIN] = 1;
    termAttr.c_cc[VTIME] = 0;
    tcsetattr(fd, TCSANOW, &termAttr);
    tcflush(fd, TCIOFLUSH);
    std::cout << port << ": serial init ok!" << endl;
    return fd;
}


/** 
 * @brief 重启定位系统,数据清零
 * @param fd 发送时使用的串口号
 */
void ppsCommSerial::RestartPos(int fd) 
{
    char tdata[16] = {'A', 'Z','e','r','o','D','r','i','f','t','F','l','a','g', '\r', '\n'};
    write(fd, tdata, 16);
    char ch;
    while(read(fd,&ch,1) != -1);
}


int main(int argc, char** argv) 
{
    // // 1.初始化ros2
    // rclcpp::init(argc, argv);

    std::cout << "pps embedded init ..." << std::endl;
    PPS_handle = pps.pps_Init(PPS_handle, "/dev/pps_uart", B115200); // TODO KERNEL=="ttyUSB*", ATTRS{idVendor}=="1a86", ATTRS{idProduct}=="7523", GROUP="users", MODE="0777",SYMLINK+="pps_uart"
    //重启定位系统函数
    pps.RestartPos(PPS_handle);
    std::cout << "port init and reset done. ^_^" << std::endl;

    return 0;
}